//
//  QLMHomeTableView.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/9/27.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMHomeTableView.h"
#import "QLMHomeTableViewCell.h"
#import "TYCyclePagerView.h"
#import "TYPageControl.h"
#import "QLMHomepageCViewCell.h"
#import "QLMNewZhenjiTabCell.h"
#import "QLMHomeButtonView.h"

@interface QLMHomeTableView()<TextInfoViewDelegate,TYCyclePagerViewDataSource,TYCyclePagerViewDelegate,QLMNewZhenjiTabCellDelegate>{
    QLMHomeTableViewCell *homecell;
    float scaleNum;
}

@property (nonatomic,strong) TYCyclePagerView *pagerView;
@property (nonatomic,strong) TYPageControl *pageControl;
@property (nonatomic,strong) NSMutableArray *urlArray;

@property (nonatomic,strong) NSMutableArray *annouceTitleArray;
@property (nonatomic,strong) NSMutableArray *annouceUrlArray;

@end

@implementation QLMHomeTableView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (void)requestData{
    [_tableview.mj_header endRefreshing];
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        _annouceTitleArray=[NSMutableArray array];
        _annouceUrlArray=[NSMutableArray array];
        
        _hotNewsArrayModel=[[QLMHotNewsArrayModel alloc] init];
        
        _tableview=[[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
        _tableview.backgroundColor=[UIColor clearColor];
        _tableview.delegate=self;
        _tableview.dataSource=self;
        _tableview.separatorStyle=UITableViewCellSeparatorStyleNone;
        _tableview.showsVerticalScrollIndicator=NO;
        _tableview.showsHorizontalScrollIndicator=NO;
        _tableview.tableFooterView=[UIView new];
        [self addSubview:_tableview];
        
        scaleNum = kScreen_width>375? 40:0;
        _urlArray = [NSMutableArray array];
    }
    
    return self;
}

- (UIButton *)acreatButton:(CGRect)aFrame title:(NSString *)aTitle image:(NSString *)imageName{
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.frame = aFrame;
    [newButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [newButton setTitle:aTitle forState:UIControlStateNormal];
    [newButton setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    newButton.backgroundColor = [UIColor whiteColor];
    newButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
    [newButton addTarget:self action:@selector(newButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return newButton;
}

- (void)newButtonAction:(UIButton *)sender{
    [_delegate didselectMore:sender.tag];
}

- (void)setHotNewsArrayModel:(QLMHotNewsArrayModel *)hotNewsArrayModel{
    _hotNewsArrayModel=hotNewsArrayModel;
    [_urlArray removeAllObjects];
    
    NSMutableArray *titlearray=[NSMutableArray array];
    NSMutableArray *annouUrlarray=[NSMutableArray array];
    for (int i=0; i<_hotNewsArrayModel.dataAnnouncement.count; i++) {
        QLMAnnouncementModel *announceModel=[[QLMAnnouncementModel alloc] initWithDictionary:_hotNewsArrayModel.dataAnnouncement[i] error:nil];
        [titlearray addObject:announceModel.announcementTitle];
        [annouUrlarray addObject:announceModel.announcementId];
    }
    
    for (int i=0; i<_hotNewsArrayModel.dataCarouselFigure.count; i++) {
        QLMCarouselFigureModel *carouseModel=[[QLMCarouselFigureModel alloc] initWithDictionary:_hotNewsArrayModel.dataCarouselFigure[i] error:nil];
        [_urlArray addObject:carouseModel.pictureUrl];
    }
    
    _annouceTitleArray=titlearray;
    _annouceUrlArray=annouUrlarray;
    
    [_tableview reloadData];
}

- (NSString *)timeWithTimeIntervalString:(NSString *)timeString{
    // 格式化时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"shanghai"];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm:ss"];
    
    // 毫秒值转化为秒
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[timeString doubleValue]/ 1000.0];
    NSString* dateString = [formatter stringFromDate:date];
    return dateString;
}

#pragma mark - didClick Notice
- (void)didClickContentAtIndex:(NSInteger)index{
//    [_delegate clickNoticeLabel:idStr];
}

#pragma mark - 轮播图
- (void)addPagerView:(UIView *)header{
    TYCyclePagerView *pagerView = [[TYCyclePagerView alloc]init];
    pagerView.frame = CGRectMake(0, 0, kScreen_width, 180+scaleNum);
    pagerView.isInfiniteLoop = YES;
    pagerView.autoScrollInterval = 3.0;
    pagerView.dataSource = self;
    pagerView.delegate = self;
    [pagerView registerClass:[QLMHomepageCViewCell class] forCellWithReuseIdentifier:@"pagecellId"];
    [header addSubview:pagerView];
    
    _pagerView = pagerView;
}

- (void)addPageControl {
    
    TYPageControl *pageControl = [[TYPageControl alloc]init];
    pageControl.frame = CGRectMake(0, CGRectGetHeight(_pagerView.frame) - 26, CGRectGetWidth(_pagerView.frame), 26);
    pageControl.currentPageIndicatorSize = CGSizeMake(8, 8);
    [_pagerView addSubview:pageControl];
    
    _pageControl = pageControl;
    _pageControl.numberOfPages = _urlArray.count;
    [_pagerView reloadData];
}

#pragma mark - TYCyclePagerViewDataSource
- (NSInteger)numberOfItemsInPagerView:(TYCyclePagerView *)pageView {
    return _urlArray.count;
}

- (UICollectionViewCell *)pagerView:(TYCyclePagerView *)pagerView cellForItemAtIndex:(NSInteger)index {
   
    QLMHomepageCViewCell *cell = [pagerView dequeueReusableCellWithReuseIdentifier:@"pagecellId" forIndex:index];
    NSString *picUrlStr=[NSString stringWithFormat:@"%@%@",kBaseURL,_urlArray[index]];
    
    //图片缓存
    [cell.pageImageview sd_setImageWithURL:[NSURL URLWithString:picUrlStr] placeholderImage:[UIImage imageNamed:@"default_bg"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        [[SDImageCache sharedImageCache] storeImage:image forKey:picUrlStr completion:nil];
        switch (cacheType) {
            case SDImageCacheTypeNone:
//                NSLog(@"现在下载，没有缓存");
                break;
            case SDImageCacheTypeDisk:
//                NSLog(@"磁盘缓存");
                break;
            case SDImageCacheTypeMemory:
//                NSLog(@"内存缓存");
                break;
            default:
                break;
        }
    }];
    
    return cell;
}

- (TYCyclePagerViewLayout *)layoutForPagerView:(TYCyclePagerView *)pageView {
    TYCyclePagerViewLayout *layout = [[TYCyclePagerViewLayout alloc]init];
    layout.itemSize = CGSizeMake(CGRectGetWidth(pageView.frame), CGRectGetHeight(pageView.frame));
    layout.itemSpacing = 0;
    layout.itemHorizontalCenter = YES;
    return layout;
}

- (void)pagerView:(TYCyclePagerView *)pageView didScrollFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    _pageControl.currentPage = toIndex;
}

- (void)pagerView:(TYCyclePagerView *)pageView didSelectedItemCell:(__kindof UICollectionViewCell *)cell atIndex:(NSInteger)index{
    [_delegate tapImageView:index];
}

#pragma mark -
- (void)didselectItem:(NSInteger)selectItemInt{
    [_delegate didselectMore:selectItemInt];
}

#pragma mark - UITableViewDatasource
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section==0) {
        return 10.f;
    }
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 10)];
    footerView.backgroundColor=[UIColor clearColor];
    footerView.userInteractionEnabled=YES;
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 180+scaleNum;
    }else if (section==1){
        return 60;
    }
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 54)];
    headerView.backgroundColor=[UIColor clearColor];
    headerView.userInteractionEnabled=YES;
 
    if (section==0) {
        
        UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 180+scaleNum)];
        imageView.backgroundColor=[UIColor whiteColor];
        [headerView addSubview:imageView];
        
        [self addPagerView:headerView];
        [self addPageControl];
    }
    
    if (section!=0) {
        CGFloat backHeight=44;
        if (section==1) {
            backHeight=60;
        }
        UIView *backView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, backHeight)];
        backView.backgroundColor=[UIColor whiteColor];
        [headerView addSubview:backView];
        
        if (section!=1) {
            UIView *lineView=[[UIView alloc] initWithFrame:CGRectMake(0, backHeight-0.2, kScreen_width, 0.2)];
            lineView.backgroundColor=[UIColor lightGrayColor];
            [headerView addSubview:lineView];
        }
    }
    
    if (section==1) {
        
        UIButton *iconBtn=[self acreatButton:CGRectMake(20, 16, 28, 28) title:nil image:@"notice"];
        iconBtn.tag=3001;
        iconBtn.backgroundColor=[UIColor clearColor];
        [headerView addSubview:iconBtn];
        
        if (_annouceTitleArray.count!=0) {
            [self createVLabelUI:headerView withModelArray:_annouceTitleArray andIdArray:_annouceUrlArray];
        }
    }
    
    if (section!=0&&section!=1) {
 
        NSString *btnTitle=@"新闻";
        if (section==4) {
            btnTitle=@"配件";
        }else if (section==3){
            btnTitle=@"整机";
        }
        
        CGRect leftButtonRect=CGRectMake(15, 10, 80, 24);
        UIButton *newsButton=[self acreatButton:leftButtonRect title:btnTitle image:@"icon"];
        newsButton.contentHorizontalAlignment=UIControlContentHorizontalAlignmentLeft;
        newsButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        newsButton.titleEdgeInsets = UIEdgeInsetsMake(0, 6, 0, 0);
        newsButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
        [headerView addSubview:newsButton];
 
        CGRect rightButtonRect=CGRectMake(kScreen_width-60-20, 10, 60, 24);
        UIButton *rightButton=[self acreatButton:rightButtonRect title:[NSString stringWithFormat:@"查看更多"] image:@"next"];
        rightButton.tag=2000+section;
        [rightButton setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
        rightButton.titleLabel.font=[UIFont systemFontOfSize:16.0f];
        rightButton.imageEdgeInsets = UIEdgeInsetsMake(0, rightButton.frame.size.width - rightButton.imageView.frame.size.width, 0, 0);
        rightButton.titleEdgeInsets = UIEdgeInsetsMake(0, 25-(rightButton.frame.size.width - rightButton.imageView.frame.size.width ), 0, 0);
        
        if (section==2) {
            [headerView addSubview:rightButton];
        }
    }
    
    return headerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }else if (section==1) {
        return 0;
    } else if(section==2){
        if (_hotNewsArrayModel.dataHotNews.count>2) {
            return 2;
        }
        if (_hotNewsArrayModel.dataHotNews.count==0) {
            return 2;
        }
        return _hotNewsArrayModel.dataHotNews.count;
    }
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        return HomeButtonHeight+45;
    }else if(indexPath.section==2){
        return 67;
    }else if(indexPath.section==1){
        return 44;
    }else if (indexPath.section==4){
        return 80+10;
    }
    return 120;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==2) {
        homecell=[QLMHomeTableViewCell cellWithTableView:tableView];
        homecell.selectionStyle=UITableViewCellSelectionStyleNone;
        
        if (_hotNewsArrayModel.dataHotNews.count!=0) {
            QLMHotNewsModel *hotnewsModel=[[QLMHotNewsModel alloc] initWithDictionary:_hotNewsArrayModel.dataHotNews[indexPath.row] error:nil];
            homecell.detailNewsLabel.font=[UIFont systemFontOfSize:16.0f];
            homecell.detailNewsLabel.text=hotnewsModel.newsTitle;
            homecell.timeLabel.text = [self timeWithTimeIntervalString:hotnewsModel.newsPubdate];
            homecell.timeLabel.font=[UIFont systemFontOfSize:14.0f];
            [homecell.iconImageview sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kBaseURL,hotnewsModel.newsPicturePath]] placeholderImage:[UIImage imageNamed:@"img_news"]];
        }

        return homecell;
    }
    
    if (indexPath.section==0||indexPath.section==4){
    
        static NSString *cellid=[NSString stringWithFormat:@"homecellid%ld%ld",(long)indexPath.section,(long)indexPath.row];
        UITableViewCell *cell=[tableView cellForRowAtIndexPath:indexPath];
        if (cell==nil) {
            cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
            cell.selectionStyle=UITableViewCellSelectionStyleNone;
        }
        
        if (indexPath.section==0) {

            for (int i=0; i<_titleArray.count; i++) {
                QLMHomeButtonView *buttonView=[[QLMHomeButtonView alloc] initWithFrame:CGRectMake(20+i*(HomeButtonHeight+20), 15, HomeButtonHeight, HomeButtonHeight+25)];
                [buttonView _setUpData:_imagenameArray[i] WithTitle:_titleArray[i]];
                buttonView.userInteractionEnabled=YES;
                buttonView.mynameBtn.tag=1000+i;
                [buttonView.mynameBtn addTarget:self action:@selector(newButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:buttonView];
            }
            
        }else if (indexPath.section==4){
            
            for (int i=0; i<5; i++) {
                CGRect rectButton=CGRectMake(2+((kScreen_width-12)/5+2)*i, 10, (kScreen_width-12)/5, 60);
                UIButton *pushButton=[self acreatButton:rectButton title:_pjtitleArray[i] image:_pjimagenameArray[i]];
                [pushButton verticalImageAndTitle:-5];
                pushButton.tag=3210+i;
                pushButton.titleLabel.font=[UIFont systemFontOfSize:16];
                [cell addSubview:pushButton];
            }
        }
        
        return cell;
    }

    QLMNewZhenjiTabCell *zhenjicell=[QLMNewZhenjiTabCell cellWithTableView:tableView];
    zhenjicell.delegate=self;
    return zhenjicell;
}

- (void)zhenjiBtnAction:(UITapGestureRecognizer *)gesture{
    [_delegate didselectMore:gesture.view.tag];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section==2) {
        [_delegate didselectTopushVC:indexPath];
    }
}

#pragma mark - TextInfoViewDelegate
- (void)handleTopEventWithURLString:(NSString *)URLString{
    NSLog(@"URLString123===%@", URLString);
    [_delegate clickNoticeLabel:URLString];
}

- (void)handleBottomEventWithURLString:(NSString *)URLString{
    NSLog(@"URLString456===%@", URLString);
    [_delegate clickNoticeLabel:URLString];
}

- (void)getBottomDataSourceModel:(DataSourceModel *)bottomDataSourceModel{
    
}

- (void)getTopDataSourceModel:(DataSourceModel *)topDataSourceModel{
    
}

- (void)createVLabelUI:(UIView *)headerView withModelArray:(NSMutableArray *)modelArray andIdArray:(NSMutableArray *)idArray{

    XLsn0wTextCarousel *view=[[XLsn0wTextCarousel alloc] initWithFrame:CGRectMake(50,10,kScreen_width-50-10, 40)];
    view.currentTextInfoView.xlsn0wDelegate = self;
    view.hiddenTextInfoView.xlsn0wDelegate = self;
    view.backgroundColor =[UIColor whiteColor];
    [headerView addSubview:view];
    
    NSMutableArray *_dataSourceArray = [NSMutableArray array];
    for (int i = 0; i < modelArray.count; i++) {

        NSString *title = [modelArray objectAtIndex:i];
        NSString *URLString = [idArray objectAtIndex:i];

        DataSourceModel *model = [DataSourceModel dataSourceModelWithType:nil title:title URLString:URLString];
        [_dataSourceArray addObject:model];
    }
    view.dataSourceArray = _dataSourceArray;
}

@end
